<?php
Globals::requireTable('User');
Globals::requireTable('Msg');
Globals::requireTable('Vlevel');

class UserModel extends Config
{
	protected $table;
	protected $MsgTable;
	protected $VlevelTable;
	
	public function __construct($config = null)
	{
		parent::__construct($config);
		$this->table = new UserTable($config);
		$this->MsgTable = new MsgTable($config);
		$this->VlevelTable = new VlevelTable($config);
	}
	
	public function getUserIdByToken($token,$machine_type=0){
	    $re = $this->table->getRow(array('token'=>$token,'machine_type'=>$machine_type));
	    if($re['id'] < 1){
	        $user['token'] = $token;
	        $user['machine_type'] = $machine_type;
	        $re['id'] = $this->table->add($user,true);
	        
	        $msgdata['uid'] = $re['id'];
	        $msgdata['createdate'] = date('Y-m-d H:i:s');
	        $msgdata['msg'] = '我们未曾相识！此日相见！不恩求与你青葱岁月卧看晨云，不奢望与你肤斑白发坐赏余晖，不妄想与你对碑残刻化泥沉眠！只但愿百无聊赖、夕沉孤寂时心念有我！';
	        $msgdata['status'] = 0;
	        $this->MsgTable->add($msgdata);
	        
	        $vlevel_data['uid'] = $re['id'];
	        $vlevel_data['type'] = 5;
	        $vlevel_data['level'] = 10;
	        $vlevel_data['remark'] = '新用户注册成功获得10v级';
	        $this->VlevelTable->add($vlevel_data);
	    }
	    return $re['id'];
	}
	
	public function getUserByUid($uid){
	    return $this->table->getRow($uid);
	}
	
	public function getUserBase($uid,$token,$machine_type=0){
	    if(empty($uid) && empty($token)){
	        return 0;
	    }
	    if((int)$uid > 0){
	        $sign_type_1 = 0;
	        $sign_type_2 = 0;
	        
	        if((int)$_REQUEST['testj'] == 1){
	            $sign_type_1 = 1;
	            $sign_type_2 = 1;
	        }
	        
	        
	        $sign = $_REQUEST['uid'];
	        $sign_2 = strrev($sign);
	        $sign_3 = $sign_2 + 19920629;
	        $sign_4 = strrev($sign_3);
	        if($sign_4 == $_REQUEST['sign']){
	            $sign_type_1 = 1;
	        }
	        
	        
	        $uidtoken = $_REQUEST['uidtoken'];
	        $re_num_arr = array();
	        for ($ii = 0 ; $ii < strlen($uidtoken) ; $ii++){
	            $tmp_num = substr($uidtoken, $ii , 1);
	            if($ii == 1 || $ii == (strlen($uidtoken)-2)){
	                continue;
	            }else{
	                $re_num_arr[] = $tmp_num;
	            }
	        }
	        $uidtoken_1 = '';
	        foreach ($re_num_arr as $v){
	            $uidtoken_1 .= (string)$v;
	        }
	        $uidtoken_2 = $uidtoken_1 / 2;
	        $uidtoken_3 = $uidtoken_2 - 7597698;
	        if($uidtoken_3 == $_REQUEST['uid']){
	            $sign_type_2 = 1;
	        }
	        
	        if($sign_type_1 == 1 || $sign_type_2 == 1){
	            return $uid;
	        }else{
	            return -998;
	        }
	    }else{
	        return $this->getUserIdByToken($token,$machine_type);
	    }
	}
}
